<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Back, Timer, View, Star, Edit, Delete, ChatDotRound, Download, Share } from '@element-plus/icons-vue';

const route = useRoute();
const router = useRouter();
const store = useStore();

// 获取课程ID
const courseId = computed(() => route.params.id);
const lessonId = computed(() => route.query.lesson);

// 课程和课时数据
const course = ref({});
const currentLesson = ref(null);
const allLessons = ref([]);
const completedLessons = ref([]);

// 视频播放器相关
const videoPlayer = ref(null);
const currentTime = ref(0);
const duration = ref(0);
const playbackRate = ref(1);

// 笔记相关
const activeTab = ref('notes');
const showNoteEditor = ref(false);
const noteContent = ref('');
const editingNoteId = ref(null);
const savingNote = ref(false);
const lessonNotes = ref([]);

// 评论相关
const showCommentEditor = ref(false);
const commentContent = ref('');
const savingComment = ref(false);
const lessonComments = ref([]);

// 资源相关
const lessonResources = ref([]);

// 格式化时间
const formatTime = (seconds) => {
  if (!seconds) return '00:00';
  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
};

// 格式化进度百分比
const percentFormat = (percentage) => {
  return '';
};

// 获取课程数据
const fetchCourseData = async () => {
  try {
    // 从store获取课程数据
    const courseData = await store.dispatch('course/fetchCourseDetail', courseId.value);
    course.value = courseData;
    
    // 获取课程大纲
    allLessons.value = [];
    
    // 将章节和课时整合到一个数组中
    courseData.outline.forEach(chapter => {
      chapter.lessons.forEach(lesson => {
        allLessons.value.push({
          ...lesson,
          chapterTitle: chapter.title
        });
      });
    });
    
    // 获取已完成的课时
    completedLessons.value = await store.dispatch('course/fetchCompletedLessons', courseId.value);
    
    // 设置当前课时
    if (lessonId.value) {
      const lesson = allLessons.value.find(l => l.id === parseInt(lessonId.value));
      if (lesson) {
        currentLesson.value = lesson;
      } else {
        currentLesson.value = allLessons.value[0];
      }
    } else {
      currentLesson.value = allLessons.value[0];
    }
    
    // 更新笔记和评论
    updateLessonNotes();
    updateLessonComments();
    updateLessonResources();
  } catch (error) {
    console.error('获取课程数据失败:', error);
    ElMessage.error('获取课程数据失败，请稍后重试');
  }
};

// 选择课时
const selectLesson = (lesson) => {
  currentLesson.value = lesson;
  
  // 更新URL，但不重新加载页面
  router.replace({
    query: { ...route.query, lesson: lesson.id }
  });
  
  // 重置视频播放器
  if (videoPlayer.value) {
    videoPlayer.value.currentTime = 0;
    videoPlayer.value.load();
    videoPlayer.value.play().catch(e => console.error('视频自动播放失败:', e));
  }
  // 更新笔记和评论
  updateLessonNotes();
  updateLessonComments();
  updateLessonResources();
};

// 检查课时是否已完成
const isLessonCompleted = (lessonId) => {
  return completedLessons.value.includes(lessonId);
};

// 处理视频时间更新
const handleTimeUpdate = () => {
  if (videoPlayer.value) {
    currentTime.value = videoPlayer.value.currentTime;
    duration.value = videoPlayer.value.duration || 0;
    
    // 如果观看进度超过90%，标记为已完成
    if (currentTime.value / duration.value > 0.9 && currentLesson.value) {
      if (!isLessonCompleted(currentLesson.value.id)) {
        completedLessons.value.push(currentLesson.value.id);
        // 更新学习进度
        updateLearningProgress();
      }
    }
  }
};

// 处理视频播放结束
const handleVideoEnded = () => {
  if (currentLesson.value && !isLessonCompleted(currentLesson.value.id)) {
    completedLessons.value.push(currentLesson.value.id);
    // 更新学习进度
    updateLearningProgress();
  }
  
  // 自动播放下一课时
  const currentIndex = allLessons.value.findIndex(lesson => lesson.id === currentLesson.value.id);
  if (currentIndex < allLessons.value.length - 1) {
    selectLesson(allLessons.value[currentIndex + 1]);
  }
};

// 更新学习进度
const updateLearningProgress = () => {
  // 这里应该调用API更新学习进度
  console.log('更新学习进度:', {
    courseId: courseId.value,
    lessonId: currentLesson.value.id,
    progress: Math.round((completedLessons.value.length / allLessons.value.length) * 100)
  });
};

// 返回课程详情页
const goBack = () => {
  router.push(`/course/${courseId.value}`);
};

// 添加笔记
const addNote = () => {
  noteContent.value = '';
  editingNoteId.value = null;
  showNoteEditor.value = true;
};

// 编辑笔记
const editNote = (note) => {
  noteContent.value = note.content;
  editingNoteId.value = note.id;
  showNoteEditor.value = true;
};

// 保存笔记
const saveNote = async () => {
  if (!noteContent.value.trim()) {
    ElMessage.warning('笔记内容不能为空');
    return;
  }
  
  savingNote.value = true;
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500));
    
    if (editingNoteId.value) {
      // 更新笔记
      const noteIndex = lessonNotes.value.findIndex(note => note.id === editingNoteId.value);
      if (noteIndex !== -1) {
        lessonNotes.value[noteIndex].content = noteContent.value;
        lessonNotes.value[noteIndex].time = new Date().toLocaleString();
      }
    } else {
      // 添加新笔记
      const newNote = {
        id: Date.now(),
        lessonId: currentLesson.value ? currentLesson.value.id : 101,
        content: noteContent.value,
        time: new Date().toLocaleString(),
        timestamp: Math.round(currentTime.value)
      };
      lessonNotes.value.unshift(newNote);
    }
    
    showNoteEditor.value = false;
    noteContent.value = '';
    editingNoteId.value = null;
    ElMessage.success(editingNoteId.value ? '笔记已更新' : '笔记已添加');
  } catch (error) {
    console.error('保存笔记失败:', error);
    ElMessage.error('保存失败，请稍后重试');
  } finally {
    savingNote.value = false;
  }
};

// 取消添加/编辑笔记
const cancelNote = () => {
  showNoteEditor.value = false;
  noteContent.value = '';
  editingNoteId.value = null;
};

// 删除笔记
const deleteNote = (note) => {
  ElMessageBox.confirm('确定要删除这条笔记吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    lessonNotes.value = lessonNotes.value.filter(item => item.id !== note.id);
    ElMessage.success('笔记已删除');
  }).catch(() => {
    // 取消删除
  });
};

// 更新当前课时的笔记
const updateLessonNotes = () => {
  if (currentLesson.value) {
    // 这里应该调用API获取当前课时的笔记
    // 模拟数据
    lessonNotes.value = [
      {
        id: 1,
        lessonId: currentLesson.value.id,
        content: '这部分内容很重要，需要重点记忆和理解。',
        time: '2023-07-15 14:30',
        timestamp: 125
      },
      {
        id: 2,
        lessonId: currentLesson.value.id,
        content: '这个公式的推导过程需要多看几遍，确保理解清楚。',
        time: '2023-07-15 14:35',
        timestamp: 310
      }
    ];
  } else {
    lessonNotes.value = [];
  }
};

// 添加评论
const addComment = () => {
  commentContent.value = '';
  showCommentEditor.value = true;
};

// 保存评论
const saveComment = async () => {
  if (!commentContent.value.trim()) {
    ElMessage.warning('评论内容不能为空');
    return;
  }
  
  savingComment.value = true;
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500));
    
    // 添加新评论
    const newComment = {
      id: Date.now(),
      lessonId: currentLesson.value ? currentLesson.value.id : 101,
      content: commentContent.value,
      time: new Date().toLocaleString(),
      user: {
        id: 1,
        name: '当前用户',
        avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
      },
      replies: []
    };
    lessonComments.value.unshift(newComment);
    
    showCommentEditor.value = false;
    commentContent.value = '';
    ElMessage.success('评论已发表');
  } catch (error) {
    console.error('发表评论失败:', error);
    ElMessage.error('发表失败，请稍后重试');
  } finally {
    savingComment.value = false;
  }
};

// 取消添加评论
const cancelComment = () => {
  showCommentEditor.value = false;
  commentContent.value = '';
};

// 更新当前课时的评论
const updateLessonComments = () => {
  if (currentLesson.value) {
    // 这里应该调用API获取当前课时的评论
    // 模拟数据
    lessonComments.value = [
      {
        id: 1,
        lessonId: currentLesson.value.id,
        content: '老师讲得非常清楚，这节课对我帮助很大！',
        time: '2023-07-10 09:15',
        user: {
          id: 2,
          name: '学习达人',
          avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
        },
        replies: [
          {
            id: 101,
            content: '我也觉得，特别是那个例题的讲解很透彻。',
            time: '2023-07-10 10:20',
            user: {
              id: 3,
              name: '知识探索者',
              avatar: 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9cpng.png'
            }
          }
        ]
      },
      {
        id: 2,
        lessonId: currentLesson.value.id,
        content: '有一个地方没太明白，15:30处的公式推导能再详细解释一下吗？',
        time: '2023-07-12 16:45',
        user: {
          id: 4,
          name: '求知者',
          avatar: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg'
        },
        replies: []
      }
    ];
  } else {
    lessonComments.value = [];
  }
};

// 更新当前课时的资源
const updateLessonResources = () => {
  if (currentLesson.value) {
    // 这里应该调用API获取当前课时的资源
    // 模拟数据
    lessonResources.value = [
      {
        id: 1,
        name: '课程讲义.pdf',
        size: '2.5MB',
        type: 'pdf',
        url: '#'
      },
      {
        id: 2,
        name: '练习题.docx',
        size: '1.2MB',
        type: 'doc',
        url: '#'
      },
      {
        id: 3,
        name: '示例代码.zip',
        size: '3.8MB',
        type: 'zip',
        url: '#'
      }
    ];
  } else {
    lessonResources.value = [];
  }
};

// 下载资源
const downloadResource = (resource) => {
  ElMessage.info(`正在下载: ${resource.name}`);
  // 这里应该实现实际的下载逻辑
};

// 设置播放速度
const setPlaybackRate = (rate) => {
  playbackRate.value = rate;
  if (videoPlayer.value) {
    videoPlayer.value.playbackRate = rate;
  }
};

// 跳转到笔记时间点
const jumpToNoteTime = (timestamp) => {
  if (videoPlayer.value && timestamp) {
    videoPlayer.value.currentTime = timestamp;
    videoPlayer.value.play().catch(e => console.error('视频播放失败:', e));
  }
};

// 监听课程ID变化
watch([courseId, lessonId], () => {
  fetchCourseData();
});

// 组件挂载时获取数据
onMounted(() => {
  fetchCourseData();
});
</script>

<style lang="scss" scoped>
.course-learn-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  
  .course-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .course-title {
      h1 {
        margin: 0 0 10px 0;
        font-size: 24px;
      }
    }
  }
  
  .course-content {
    display: flex;
    gap: 20px;
    
    .main-content {
      flex: 1;
      
      .video-container {
        background-color: #000;
        border-radius: 8px;
        overflow: hidden;
        margin-bottom: 20px;
        
        .video-player {
          width: 100%;
          max-height: 600px;
        }
        
        .video-controls {
          padding: 15px;
          background-color: #f5f7fa;
          
          .progress-info {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
            font-size: 14px;
            color: #606266;
          }
        }
      }
      
      .lesson-info {
        background-color: #fff;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 20px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
        
        h2 {
          margin: 0 0 15px 0;
          font-size: 20px;
        }
        
        .lesson-meta {
          display: flex;
          gap: 20px;
          margin-bottom: 15px;
          color: #606266;
          font-size: 14px;
          
          span {
            display: flex;
            align-items: center;
            gap: 5px;
          }
        }
        
        .lesson-description {
          color: #303133;
          line-height: 1.6;
        }
      }
      
      .lesson-tabs {
        background-color: #fff;
        border-radius: 8px;
        padding: 20px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
        
        .notes-container,
        .discussions-container,
        .resources-container {
          .notes-header,
          .discussions-header,
          .resources-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            
            h3 {
              margin: 0;
              font-size: 18px;
            }
          }
          
          .note-editor,
          .comment-editor {
            margin-bottom: 20px;
            
            .note-actions,
            .comment-actions {
              display: flex;
              justify-content: flex-end;
              gap: 10px;
              margin-top: 10px;
            }
          }
          
          .notes-list,
          .comments-list,
          .resources-list {
            .note-item,
            .comment-item,
            .resource-item {
              background-color: #f5f7fa;
              border-radius: 8px;
              padding: 15px;
              margin-bottom: 15px;
              
              .note-header,
              .comment-header,
              .resource-header {
                display: flex;
                justify-content: space-between;
                margin-bottom: 10px;
                
                .note-meta,
                .comment-meta,
                .resource-meta {
                  display: flex;
                  gap: 15px;
                  color: #909399;
                  font-size: 14px;
                  
                  .note-timestamp {
                    cursor: pointer;
                    color: #1e83ec;
                    
                    &:hover {
                      text-decoration: underline;
                    }
                  }
                }
                
                .note-actions,
                .comment-actions,
                .resource-actions {
                  display: flex;
                  gap: 5px;
                }
              }
              
              .note-content,
              .comment-content {
                color: #303133;
                line-height: 1.6;
              }
              
              .comment-user {
                display: flex;
                gap: 10px;
                margin-bottom: 10px;
                
                .user-info {
                  .user-name {
                    font-weight: 500;
                    margin-bottom: 5px;
                  }
                  
                  .comment-time {
                    color: #909399;
                    font-size: 12px;
                  }
                }
              }
              
              .comment-replies {
                margin-top: 15px;
                padding-top: 15px;
                border-top: 1px solid #ebeef5;
                
                .reply-item {
                  background-color: #fff;
                  border-radius: 8px;
                  padding: 12px;
                  margin-bottom: 10px;
                  
                  &:last-child {
                    margin-bottom: 0;
                  }
                  
                  .reply-user {
                    display: flex;
                    gap: 10px;
                    margin-bottom: 8px;
                    
                    .user-info {
                      .user-name {
                        font-weight: 500;
                        margin-bottom: 3px;
                      }
                      
                      .reply-time {
                        color: #909399;
                        font-size: 12px;
                      }
                    }
                  }
                  
                  .reply-content {
                    color: #303133;
                    line-height: 1.6;
                  }
                }
              }
              
              .resource-info {
                display: flex;
                align-items: center;
                gap: 10px;
                
                .resource-icon {
                  font-size: 24px;
                  color: #1e83ec;
                }
                
                .resource-details {
                  flex: 1;
                  
                  .resource-name {
                    font-weight: 500;
                    margin-bottom: 5px;
                  }
                  
                  .resource-size {
                    color: #909399;
                    font-size: 12px;
                  }
                }
                
                .resource-download {
                  color: #1e83ec;
                  cursor: pointer;
                  
                  &:hover {
                    color: #1976d2;
                  }
                }
              }
            }
            
            .empty-notes,
            .empty-comments,
            .empty-resources {
              text-align: center;
              padding: 30px 0;
              color: #909399;
              font-size: 14px;
            }
          }
        }
      }
    }
    
    .course-sidebar {
      width: 300px;
      flex-shrink: 0;
      
      .course-outline {
        background-color: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
        margin-bottom: 20px;
        
        .outline-header {
          padding: 15px;
          border-bottom: 1px solid #ebeef5;
          
          h3 {
            margin: 0;
            font-size: 18px;
          }
          
          .course-progress {
            margin-top: 10px;
            
            .progress-text {
              display: flex;
              justify-content: space-between;
              margin-bottom: 5px;
              font-size: 14px;
              color: #606266;
            }
          }
        }
        
        .outline-content {
          max-height: 500px;
          overflow-y: auto;
          
          .chapter-item {
            .chapter-header {
              padding: 12px 15px;
              background-color: #f5f7fa;
              font-weight: 500;
              cursor: pointer;
              display: flex;
              justify-content: space-between;
              align-items: center;
              
              .chapter-title {
                display: flex;
                align-items: center;
                gap: 5px;
              }
              
              .chapter-info {
                font-size: 12px;
                color: #909399;
              }
              
              &:hover {
                background-color: #ecf5ff;
              }
            }
            
            .lesson-list {
              .lesson-item {
                padding: 10px 15px 10px 30px;
                cursor: pointer;
                display: flex;
                align-items: center;
                border-bottom: 1px solid #ebeef5;
                
                .lesson-status {
                  margin-right: 10px;
                  color: #67c23a;
                }
                
                .lesson-title {
                  flex: 1;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                }
                
                .lesson-duration {
                  font-size: 12px;
                  color: #909399;
                  margin-left: 10px;
                }
                
                &:hover {
                  background-color: #f5f7fa;
                }
                
                &.active {
                  background-color: #ecf5ff;
                  color: #1e83ec;
                  
                  .lesson-duration {
                    color: #1e83ec;
                  }
                }
                
                &.completed {
                  .lesson-title {
                    color: #67c23a;
                  }
                }
              }
            }
          }
        }
      }
      
      .playback-settings {
        background-color: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
        padding: 15px;
        
        h3 {
          margin: 0 0 15px 0;
          font-size: 16px;
        }
        
        .playback-rates {
          display: flex;
          flex-wrap: wrap;
          gap: 10px;
          
          .rate-btn {
            flex: 1;
            min-width: 50px;
            text-align: center;
            
            &.active {
              color: #1e83ec;
              border-color: #1e83ec;
            }
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .course-content {
    flex-direction: column;
    
    .course-sidebar {
      width: 100% !important;
    }
  }
}
</style> 